package com.shr.code_interview;

import java.util.ArrayList;
import java.util.List;

public class Solution_29 {
	public ArrayList<Integer> printMatrix(int[][] matrix) {

		ArrayList<Integer> list = new ArrayList<>();
		int start = 0;
		while (matrix.length > 2 * start && matrix[0].length > 2 * start) {
			List<Integer> aArray = printClockWise(matrix, start);
			list.addAll(aArray);
			start++;
		}
		return list;
	}

	private List<Integer> printClockWise(int[][] matrix, int start) {
		List<Integer> aArray = new ArrayList<>();
		for (int i = start; i <= matrix[start].length - start - 1; i++) {
			aArray.add(matrix[start][i]);
		}
		int colStart = matrix[start].length - start - 1;
		int rowStart2 = matrix.length - start - 1;

		if (start < rowStart2) {
			for (int i = start + 1; i <= matrix.length - start - 1; i++) {
				aArray.add(matrix[i][colStart]);
			}
		}

		if (start < rowStart2 && start < colStart) {
			for (int i = colStart - 1; i >= start; i--) {
				aArray.add(matrix[rowStart2][i]);
			}
		}
		if (start < colStart && start < rowStart2 - 1) {
			for (int i = rowStart2 - 1; i > start; i--) {
				aArray.add(matrix[i][start]);
			}
		}
		return aArray;
	}
}
